package com.say.controller;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.say.bean.common.Response;
import com.say.utils.MessageHandlerUtil;
import com.say.utils.weixin.SHA1Util;
import com.say.utils.weixin.WeixinUtil;
 

@Controller
@RequestMapping("/wechat")
public class WechatController extends BaseController {
	
    
	/**
	 *
	 *类说明：配置外网地址的时候进入doGet
	 */
	@RequestMapping(value = "/insertWechat", method = RequestMethod.GET)
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.info("开始校验签名");
		/**
		 * 接收微信服务器发送请求时传递过来的4个参数
		 */
		String signature = request.getParameter("signature");// 微信加密签名signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		String timestamp = request.getParameter("timestamp");// 时间戳
		String nonce = request.getParameter("nonce");// 随机数
		String echostr = request.getParameter("echostr");// 随机字符串
		String mySignature = "";
		if (timestamp != null && nonce != null) {
			// 排序
			String sortString = new SHA1Util().sort(WeixinUtil.TOKEN, timestamp, nonce);
			// 加密
			mySignature =  new SHA1Util().sha1(sortString);
		}
		// 校验签名
		if (mySignature != null && mySignature != ""
				&& mySignature.equals(signature)) {
			logger.info("签名校验通过。");
			// 如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
			// response.getWriter().println(echostr);
			response.getWriter().write(echostr);
		} else {
			logger.info("签名校验失败.");
		}
	}

	@RequestMapping(value = "/insertWechat", method = RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 //doGet(request, response);
		//  接收、处理、响应由微信服务器转发的用户发送给公众帐号的消息
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
			Map<String,String> map = MessageHandlerUtil.parseXml(request);
			logger.info(map.toString());
			String	result = MessageHandlerUtil.buildXml(map);
            logger.info("result："+result);
			response.getWriter().println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
    @RequestMapping(value = "/wxjssdk")
    @ResponseBody
    public Response wxjssdk(String url) {
    	Response response = new  Response();
    	Map<String, Object> map=new HashMap<String, Object>();
		try {
			map = WeixinUtil.getSignature(url);
			response.success(map,"操作成功");
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.failure("失败");
    	return response;
    }
    
    
    
	

	
}
